<template>
    <el-container class="gross-profit-calculator">
        <el-header ref="pageHeaderRef" class="page-header">
            <div class="title-area">
                <h1 class="page-title">澳玛小红书投放评估工具</h1>
                <span class="version-info">版本号: 1.3</span>
                <span class="upgrade-info">时间: 2025/07/28</span>
            </div>
            <div class="user-info">
                <span>{{ userInfo?.organizationName || '用户' }}</span>
                <el-button type="danger" size="small" @click="handleLogout">退出登录</el-button>
            </div>
        </el-header>

        <el-main class="main-content">
            <el-card class="!border-none mt-4" shadow="never">
                <div ref="buttonAreaRef" style="display: flex;">
                    <el-button type="primary" @click="handleImport" v-if="userInfo?.type != 1">
                        导入小红书笔记数据
                    </el-button>
                    <el-button type="primary" @click="handleImportLaunch" v-if="userInfo?.type != 1">
                        导入聚光投放数据
                    </el-button>
                    <el-select v-if="userInfo?.type == 1" v-model="queryParams.organizationCode" filterable
                        placeholder="请选择机构" style="width: 240px;margin-left: 20px;" @change="changeSelect" clearable>
                        <el-option v-for="item in options" :key="item.id" :label="item.label" :value="item.value" />
                    </el-select>
                    <div style="margin-left: 20px;">
                        <el-date-picker
                            v-model="queryParams.date"
                            type="month"
                            placeholder="请选择月份"
                            style="width: 180px;"
                            @clear="onSearchFun"
                        />
                        <el-button type="primary" style="margin-left: 10px;" @click="onSearchFun">搜素</el-button>
                    </div>
                </div>
                <div style="margin-top: 20px;">
                    <div >
                        <el-table ref="tableRef" :data="tableData" :height="tableHeight" style="width: 100%;" border @scroll.native="handleScroll" infinite-scroll-distance="50"
                            :row-class-name="getRowClassName" header-cell-class-name="headerClass" cell-class-name="cellClass">
                            <!-- v-infinite-scroll="loadMore"  -->
                            <el-table-column prop="organizationName" label="机构" width="70" align="center" />
                            <el-table-column prop="title" label="标题" width="300" align="center" show-overflow-tooltip>
                                <template #default="{ row }">
                                    {{ row.title }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="releaseDate" label="发布时间" width="138" align="center">
                                <template #default="{ row }">
                                    {{ row.releaseDate ? timeFormat(row.releaseDate, 'yyyy-mm-dd hh:MM') : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="type" label="内容类型" width="70" align="center" />
                            <el-table-column prop="updateDate" label="笔记更新时间" width="138" align="center">
                                <template #default="{ row }">
                                    {{ row.updateDate ? timeFormat(row.updateDate, 'yyyy-mm-dd hh:MM') : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="firstSnapshotLookCount" label="观看量" width="60" align="center" />
                            <el-table-column prop="firstSnapshotPerCapitaLookTime" label="人均观看时长" width="60" align="center" />
                            <el-table-column prop="firstSnapshotGiveCount" label="点赞" width="50" align="center" />
                            <el-table-column prop="firstSnapshotCollectCount" label="收藏" width="50" align="center" />
                            <el-table-column prop="firstSnapshotCommentCount" label="评论" width="50" align="center" />
                            <el-table-column prop="firstSnapshotShareCount" label="分享" width="50" align="center" />
                            <el-table-column prop="firstSnapshotAddFansCount" label="涨粉" width="50" align="center" />

                            <el-table-column label="投流前总互动量" width="68" align="center">
                                <template #default="{ row }">
                                    {{ (parseInt(row.firstSnapshotGiveCount) || 0) +
                                        (parseInt(row.firstSnapshotCollectCount) || 0) +
                                        (parseInt(row.firstSnapshotCommentCount) || 0) +
                                        (parseInt(row.firstSnapshotShareCount) || 0) +
                                        (parseInt(row.firstSnapshotAddFansCount) || 0) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="投放数据更新时间" width="138" align="center">
                                <template #default="{ row }">
                                    {{ row.isFirstDeployTraffic != 10 && row.launchDate ? timeFormat(row.launchDate,
                                    'yyyy-mm-dd hh:MM') : '' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="第1次投流" align="center">
                                <el-table-column label="是否第1次投放" width="100" align="center">
                                    <template #default="{ row }">
                                        <el-tag
                                            :type="row.isFirstDeployTraffic == 30 ? 'success' : row.isFirstDeployTraffic == 20 ? 'info' : 'error'"
                                            v-if="row.isFirstDeployTraffic == 30 || row.isFirstDeployTraffic == 20 || row.isFirstDeployTraffic == 25">
                                            {{ getAuditText(row.isFirstDeployTraffic) }}
                                        </el-tag>
                                        <el-tag
                                            :type="'error'"
                                            v-if="row.isFirstDeployTraffic == 10" @click="handleFirstChangeType(row)" style="cursor: pointer;">
                                            {{ getAuditText(row.isFirstDeployTraffic) }}
                                        </el-tag>
                                        <span v-if="row.isFirstDeployTraffic != 10 && row.isFirstDeployTraffic != 20 && row.isFirstDeployTraffic != 25 && row.isFirstDeployTraffic != 30"></span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="投流日期" width="138" align="center">
                                    <template #default="{ row }">
                                        {{ row.isFirstDeployTraffic == 30 && row.firstDeployTrafficDate ?
                                        timeFormat(row.firstDeployTrafficDate, 'yyyy-mm-dd hh:MM') : '' }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="消耗金额" width="60" align="center">
                                    <template #default="{ row }">
                                        {{ row.isFirstDeployTraffic != 30 ? '' : row.launchPrice ? row.launchPrice : 0 }}
                                    </template>
                                </el-table-column>


                                <el-table-column label="新增观看量" width="60" align="center">
                                    <!-- 自定义表头 -->
                                    <template #default="{ row }">
                                        {{ row.isFirstDeployTraffic != 30 ? '' : row.firstDeployTrafficLookCount ? row.firstDeployTrafficLookCount : 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="人均观看时长变化量" width="88" align="center">
                                    <template #default="{ row }">
                                        {{ row.isFirstDeployTraffic != 30 ? '' : row.firstDeployTrafficLookTime ? row.firstDeployTrafficLookTime : 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="新增互动量" width="60" align="center">
                                    <template #default="{ row }">
                                        {{ row.isFirstDeployTraffic != 30 ? '' : row.firstDeployTrafficInteractionCount ? row.firstDeployTrafficInteractionCount : 0 }}
                                    </template>
                                </el-table-column>
                               
                                <el-table-column label="开口量" width="60" align="center">
                                    <template #default="{ row }">
                                        {{ row.isFirstDeployTraffic != 30 ? '' : row.openingQuantity ? row.openingQuantity : 0 }}
                                    </template>
                                </el-table-column>
                            </el-table-column>
                            <el-table-column label="第2次投流" align="center">
                                <el-table-column label="是否第2次投放" width="100" align="center">
                                    <template #default="{ row }">
                                        <el-tag :type="row.isSecondDeployTraffic == 30 ? 'success' : 'info'"
                                            v-if="row.isSecondDeployTraffic == 30 || row.isSecondDeployTraffic == 20">
                                            {{ getAuditText(row.isSecondDeployTraffic) }}
                                        </el-tag>
                                        <el-tag :type="'error'"
                                            v-if="row.isSecondDeployTraffic == 10" @click="handleSecondChangeType(row)" style="cursor: pointer;">
                                            {{ getAuditText(row.isSecondDeployTraffic) }}
                                        </el-tag>
                                        <span v-if="row.isSecondDeployTraffic != 10 && row.isSecondDeployTraffic != 20 && row.isSecondDeployTraffic != 30"></span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="投流日期"  align="center" width="200">
                                    <template #default="{ row }">
                                        <div style="width: 100%;display: flex;gap: 0 10px;align-items: center;"
                                            v-if="row.isSecondDeployTraffic == 20">
                                            <el-date-picker v-model.lazy="row.editSecondDeployTrafficDate" type="datetime"
                                                placeholder="选择日期" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                                size="small" style="width: 140px;" :disabled-date="(time) => time.getTime() > Date.now()" prefix-icon="null"/>
                                            <el-button type="primary" size="small" @click="saveSecondDeployDate(row)"
                                                style="width: 40px;">
                                                保存
                                            </el-button>
                                        </div>
                                        <div style="margin-top: 4px; font-size: 12px; color: #666;"
                                            v-if="row.isSecondDeployTraffic == 30 && row.secondDeployTrafficDate != '' && row.secondDeployTrafficDate != null">
                                            {{ row.secondDeployTrafficDate ? timeFormat(row.secondDeployTrafficDate,
                                            'yyyy-mm-dd hh:MM') : '' }}
                                        </div>
                                    </template>
                                </el-table-column>

                                <el-table-column label="消耗金额" width="60" align="center">
                                    <template #default="{ row }">
                                        {{ row.isSecondDeployTraffic != 30 ? '' : row.secondLaunchPrice ? row.secondLaunchPrice : 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="新增观看量" width="60" align="center">
                                    <template #default="{ row }">

                                        {{ row.isSecondDeployTraffic != 30 ? '' : row.secondDeployTrafficLookCount ? row.secondDeployTrafficLookCount : 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="人均观看时长变化量" width="80" align="center">
                                    <template #default="{ row }">
                                        {{ row.isSecondDeployTraffic != 30 ? '' : row.secondDeployTrafficLookTime ? row.secondDeployTrafficLookTime : 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="新增互动量" width="60" align="center">
                                    <template #default="{ row }">
                                        {{ row.isSecondDeployTraffic != 30 ? '' : row.secondDeployTrafficInteractionCount ? 
                                        row.secondDeployTrafficInteractionCount : 0 }}
                                    </template>
                                </el-table-column>
                                
                                <el-table-column label="开口量" width="60" align="center">
                                    <template #default="{ row }">
                                        {{ row.isSecondDeployTraffic != 30 ? '' : row.secondOpeningQuantity ? row.secondOpeningQuantity : 0 }}
                                    </template>
                                </el-table-column>
                            </el-table-column>
                            <el-table-column label="第3次投流" align="center">
                                <el-table-column label="是否第3次投放" width="100" align="center">
                                    <template #default="{ row }">
                                        <el-tag :type="row.isThreeDeployTraffic == 30 ? 'success' : 'info'"
                                            v-if="row.isThreeDeployTraffic == 30 || row.isThreeDeployTraffic == 20">
                                            {{ getAuditText(row.isThreeDeployTraffic) }}
                                        </el-tag>
                                        <el-tag :type="'error'"
                                            v-if="row.isThreeDeployTraffic == 10" @click="handleThreeChangeType(row)" style="cursor: pointer;">
                                            {{ getAuditText(row.isThreeDeployTraffic) }}
                                        </el-tag>
                                        <span v-if="row.isThreeDeployTraffic != 10 && row.isThreeDeployTraffic != 20 && row.isThreeDeployTraffic != 30"></span>
                                        
                                    </template>
                                </el-table-column>
                                <el-table-column label="投流日期" width="200" align="center">
                                    <template #default="{ row }">
                                        <div style="width: 100%;display: flex;gap: 0 10px;align-items: center;"
                                            v-if="row.isThreeDeployTraffic == 20">
                                            <el-date-picker v-model="row.editThreeDeployTrafficDate" type="datetime"
                                                placeholder="选择日期" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                                size="small" style="width: 140px;" :disabled-date="(time) => time.getTime() > Date.now()" prefix-icon="null"/>
                                            <el-button type="primary" size="small" @click="saveThreeDeployDate(row)"
                                                style="width: 40px;">
                                                保存
                                            </el-button>
                                        </div>
                                        <div style="margin-top: 4px; font-size: 12px; color: #666;"
                                            v-if="row.isThreeDeployTraffic == 30 && row.threeDeployTrafficDate != '' && row.threeDeployTrafficDate != null">
                                            {{ row.threeDeployTrafficDate ? timeFormat(row.threeDeployTrafficDate,
                                            'yyyy-mm-dd hh:MM') : '' }}
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="消耗金额" width="60" align="center">
                                    <template #default="{ row }">
                                        {{ row.isThreeDeployTraffic != 30 ? '' : row.threeLaunchPrice ? row.threeLaunchPrice : 0 }}
                                    </template>
                                </el-table-column>


                                <el-table-column label="新增观看量" width="60" align="center">
                                    <template #default="{ row }">

                                        {{ row.isThreeDeployTraffic != 30 ? '' : row.threeDeployTrafficLookCount ? row.threeDeployTrafficLookCount : 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="人均观看时长变化量" width="80" align="center">
                                    <template #default="{ row }">
                                        {{ row.isThreeDeployTraffic != 30 ? '' : row.perCapitaLookTime ? row.perCapitaLookTime : 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="新增互动量" width="60" align="center">
                                    <template #default="{ row }">

                                        {{ row.isThreeDeployTraffic != 30 ? '' : row.threeDeployTrafficInteractionCount ? row.threeDeployTrafficInteractionCount : 0 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="开口量" width="60" align="center">
                                    <template #default="{ row }">

                                        {{ row.isThreeDeployTraffic != 30 ? '' : row.threeOpeningQuantity ? row.threeOpeningQuantity : 0 }}
                                    </template>
                                </el-table-column>
                            </el-table-column>
                            <el-table-column prop="lookCount" label="总观看量" width="120" align="center" />
                            <el-table-column prop="interactionCount" label="总互动量" width="120" align="center" />
                            
                            <el-table-column label="操作" width="120" fixed="right" align="center">
                                <template #default="{ row }">
                                    <el-button type="danger" @click="handleDelete(row)">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>

            </el-card>
            <templateImport ref="importRef" @uploadSuccessFun="getList" :action="batchImport" />
            <templateImport ref="importLaunchRef" @uploadSuccessFun="getList" :action="batchImportLaunch" />

            <!-- 更改开口量弹窗 -->
            <el-dialog v-model="dialogVisible" title="更改开口量" width="400px" :before-close="cancelDialog">
                <div class="dialog-content">
                    <el-form label-width="80px">
                        <el-form-item label="开口量:">
                            <el-input v-model="openingQuantityInput" placeholder="请输入开口量" type="number" clearable />
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="cancelDialog">取消</el-button>
                        <el-button type="primary" @click="saveOpeningAmount">保存</el-button>
                    </div>
                </template>
            </el-dialog>
        </el-main>
    </el-container>
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, onUnmounted, shallowRef, reactive } from 'vue'
import { ElMessage, ElMessageBox, ElNotification, ElLoading } from 'element-plus'
import type { UploadProps, UploadRawFile } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import feedback from '@/utils/feedback'
import { usePaging } from '@/hooks/usePaging'
import { articleList, articleEdit, articleAudit, setSecondDeployTrafficDate, deleteArticle, setThreeDeployTrafficDate, editFirstDeployTraffic, editSecondDeployTraffic, editThreeDeployTraffic } from '@/api/port'
import { timeFormat } from '@/utils/validate'
import pagination from '../components/pagination/index.vue'


const options = ref([
    {
        id: 1,
        value: 'bjjingdian',
        label: '北京经典'
    },
    {
        id: 2,
        value: 'bjxingguang',
        label: '北京星光'
    },
    {
        id: 3,
        value: 'bjwangjing',
        label: '北京望京'
    },
    {
        id: 4,
        value: 'gznanguohui',
        label: '广州南国会'
    },
    {
        id: 5,
        value: 'gzbaoli',
        label: '广州保利'
    },
    {
        id: 6,
        value: 'gzjingdian',
        label: '广州经典'
    },
    {
        id: 7,
        value: 'njxingguang',
        label: '南京星光'
    },
    {
        id: 8,
        value: 'sznanshan',
        label: '深圳南山'
    },
    {
        id: 9,
        value: 'szxinghe',
        label: '深圳星河'
    },
    {
        id: 10,
        value: 'nbxingguang',
        label: '宁波星光'
    },
    {
        id: 11,
        value: 'qdxingguang',
        label: '青岛星光'
    },
    {
        id: 12,
        value: 'czxingguang',
        label: '常州星光'
    },
    {
        id: 13,
        value: 'ycxingguang',
        label: '银川星光'
    },
    {
        id: 14,
        value: 'zzxingguang',
        label: '郑州星光'
    }
])
// 修正导入路径,确保路径正确指向uploadFile.vue组件
import templateImport from '../components/upload/uploadFile.vue' // 导入弹窗
const importRef = shallowRef<InstanceType<typeof templateImport>>()

// 导入弹窗
const handleImport = async () => {
    importRef.value && importRef.value.open()
}
const importLaunchRef = shallowRef<InstanceType<typeof templateImport>>()
const handleImportLaunch = async () => {
    importLaunchRef.value && importLaunchRef.value.open()
}
const batchImportLaunch = ref('batchImportLaunch')
const batchImport = ref('batchImport')


const getAuditText = (status: any): string => {
    const statusMap: Record<number, string> = {
        10: '未达标',
        20: '已达标待投放',
        25: '投放未成功',
        30: '已投放',
        40: ''
    }
    return statusMap[status] || ''
}
// 弹窗相关状态
const dialogVisible = ref(false)
const currentRow = ref<any>(null)
const openingQuantityInput = ref('')


// 保存开口量
const saveOpeningAmount = async () => {
    if (!openingQuantityInput.value || openingQuantityInput.value.trim() === '') {
        ElMessage.warning('请输入开口量')
        return
    }
    try {
        const res = await articleEdit({
            articleId: currentRow.value.id,
            openingQuantity: Number(openingQuantityInput.value)
        })
        console.log(res)
        ElMessage.success('开口量保存成功')
        dialogVisible.value = false
        // 刷新列表
        getDataList()
    } catch (error) {
        ElMessage.error('开口量保存失败')
    }
}

// 取消弹窗
const cancelDialog = () => {
    dialogVisible.value = false
    openingQuantityInput.value = ''
    currentRow.value = null
}

// 保存第二次投流日期
const saveSecondDeployDate = async (row: any) => {
    // 校验日期是否为空
    if (!row.editSecondDeployTrafficDate) {
        ElMessage.warning('请选择投流日期')
        return
    }
    // 校验日期是否大于当时时间
    if (new Date(row.editSecondDeployTrafficDate) > new Date()) {
        ElMessage.warning('请选择小于等于当前时间的日期时间')
        return
    }
    
    let date = new Date(row.editSecondDeployTrafficDate)
    try {
        const res = await setSecondDeployTrafficDate({
            articleId: row.id,
            secondDeployTrafficDateStr: timeFormat(date.getTime(), 'yyyy-mm-dd') + ' 00:00:00'
        })

        if (res.data.code === 0) {
            ElMessage.success('投流日期保存成功')
            // 更新当前行的显示日期
            row.secondDeployTrafficDate = row.editSecondDeployTrafficDate
            // 刷新列表数据
            getDataList()
        } else {
            ElMessage.error(res.data.msg || '保存失败')
        }
    } catch (error) {
        ElMessage.error('保存失败，请重试')
        console.error('保存投流日期失败:', error)
    }
}

// 保存第二次投流日期
const saveThreeDeployDate = async (row: any) => {
    // 校验日期是否为空
    if (!row.editThreeDeployTrafficDate) {
        ElMessage.warning('请选择投流日期')
        return
    }
    // 校验日期是否大于当时时间
    if (new Date(row.editThreeDeployTrafficDate) > new Date()) {
        ElMessage.warning('请选择小于等于当前时间的日期时间')
        return
    }
    let date = new Date(row.editThreeDeployTrafficDate)
    try {
        const res = await setThreeDeployTrafficDate({
            articleId: row.id,
            threeDeployTrafficDateStr: timeFormat(date.getTime(), 'yyyy-mm-dd') + ' 00:00:00'
        })

        if (res.data.code === 0) {
            ElMessage.success('投流日期保存成功')
            // 更新当前行的显示日期
            row.threeDeployTrafficDate = row.editThreeDeployTrafficDate
            // 刷新列表数据
            getDataList()
        } else {
            ElMessage.error(res.data.msg || '保存失败')
        }
    } catch (error) {
        ElMessage.error('保存失败，请重试')
        console.error('保存投流日期失败:', error)
    }
}

// DOM元素引用
const pageHeaderRef = ref<HTMLElement>()
const buttonAreaRef = ref<HTMLElement>()

// 各部分高度的响应式变量
const headerHeight = ref(70) // 默认值
const buttonAreaHeight = ref(52) // 默认值
const safetyMargin = ref(40) // 安全边距

// 计算表格最大高度
const calculateTableHeight = () => {
    // 获取实际DOM元素高度
    const actualHeaderHeight = pageHeaderRef.value?.offsetHeight || headerHeight.value
    const actualButtonHeight = buttonAreaRef.value?.offsetHeight || 0

    // 更新响应式变量
    headerHeight.value = actualHeaderHeight
    buttonAreaHeight.value = actualButtonHeight

    // 计算总的减去高度
    const totalReduceHeight = actualHeaderHeight + actualButtonHeight + safetyMargin.value + 100 // 40px为额外间距

    return `calc(100vh - ${totalReduceHeight}px)`
}

// 表格高度
const tableHeight = ref(calculateTableHeight())

// 重新计算表格高度的方法
const recalculateTableHeight = () => {
    tableHeight.value = calculateTableHeight()
}

const router = useRouter()
const userStore = useUserStore()
const userInfo = ref<any>({})
userInfo.value = userStore.userInfo || JSON.parse(localStorage.getItem('userInfo') || '{}')
console.log(localStorage.getItem('userInfo'))
console.log(userInfo.value)
// 退出登录
const handleLogout = async () => {
    try {
        await ElMessageBox.confirm(
            '确定要退出登录吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        // 使用store退出登录
        userStore.logout()
        ElMessage.success('退出登录成功')
        // 跳转到登录页
        router.push('/login')
    } catch {
        // 用户取消退出
    }
}

// 页面加载时初始化用户信息
onMounted(() => {
    userStore.initUserInfo()
    // 等待DOM渲染完成后重新计算表格高度
    nextTick(() => {
        recalculateTableHeight()
    })

    // 监听窗口大小变化
    window.addEventListener('resize', recalculateTableHeight)
})

// 组件卸载时清理事件监听
onUnmounted(() => {
    window.removeEventListener('resize', recalculateTableHeight)
})
// 获取行类名
const getRowClassName = ({ row }: { row: any }) => {
    if (row.isFirstDeployTraffic == 20) {
        return 'status-pending'
    } else if (row.isFirstDeployTraffic == 30) {
        return 'status-processed'
    }
    return ''
}
// 表格数据
const queryParams = ref({
    organizationCode: '',
    date: ''
})

const tableData = ref<Array<any>>([])
const page = ref(0)
const pageSize = 20
// const loading = ref(false)
const tableRef = ref()
const count = ref(0)
const getDataList = async () => {
    // loading.value = true
    
    let date = new Date(queryParams.value.date)
    let obj = ref({
        page: page.value,
        pageSize: pageSize,
        organizationCode: queryParams.value.organizationCode,
        date: queryParams.value.date && queryParams.value.date != '' ? timeFormat(date.getTime(), 'yyyy-mm') : '' 
    })
    
    const res = await articleList(obj.value)
    console.log('res======================================', res)
    if (res.data.code == 0) {
        // loading.value = false
        count.value = res.data.count
        tableData.value = [...tableData.value,...res.data.data]
        if (tableData.value && Array.isArray(tableData.value)) {
            tableData.value.forEach((row: any) => {
                // 初始化编辑用的日期字段，如果已有值则使用现有值，否则为空
                if (!row.editSecondDeployTrafficDate) {
                    row.editSecondDeployTrafficDate = row.secondDeployTrafficDate || ''
                }
                if (!row.editThreeDeployTrafficDate) {
                    row.editThreeDeployTrafficDate = row.threeDeployTrafficDate || ''
                }
            })
        }
    
    }
}

// 监听滚动
const scrollTimer = ref(null) as any
const handleScroll = (e: Event) => {
    // console.log('滚动事件:', e)
    // console.log('事件目标:', e.target)
    const target = e as any
    
    
    //这是使用setTimeOut函数来延迟执行，以便在滚动表格的时候节省资源和优化性能
      //设置一个定时器scrollTimer，判断如果之前设置过定时器会清除之前的定时器，以免多次触发滚动事件
    if (scrollTimer.value) {
        clearTimeout(scrollTimer.value);
    }
      //设置定时器scrollTimer延迟200毫秒后执行回调函数
    scrollTimer.value = setTimeout(() => {
        const tableEl = tableRef.value.$el    //表格的DOM元素
        // console.log('tableEl======================',tableEl)
        
        // 尝试多种方式获取滚动容器
        let scrollContainer = tableEl.querySelector('.el-scrollbar__view')
        let tableHeader = tableEl.querySelector('.el-table__header-wrapper')
        // console.log('tableHeader高度信息:', {
        //     offsetHeight: tableHeader?.offsetHeight,
        //     clientHeight: tableHeader?.clientHeight,
        //     scrollHeight: tableHeader?.scrollHeight,
        //     getBoundingClientRect: tableHeader?.getBoundingClientRect().height
        // })
        const scrollContentHeight = scrollContainer.scrollHeight  //获取表格内容的高度，即所有行的高度
        //判断是否到达底部并且当前没有正在加载更多数据，如果是，则执行方法loadMoreData()
        // console.log(target.scrollTop + tableEl.getBoundingClientRect().height - tableHeader?.getBoundingClientRect().height, scrollContentHeight)
        if(count.value > tableData.value.length ){
            if (target.scrollTop + tableEl.getBoundingClientRect().height - tableHeader?.getBoundingClientRect().height >= scrollContentHeight - 5) {
                page.value++
                getDataList()
            }
        }
        //将当前滚动位置保存到组件实例的scrollPosition中，以便下次执行定时器能够正确判断滚动事件
        // scrollPosition = scrollTop
    },200)
}
// const loadMore = () => {
//     console.log('====================================到底了')
//   if (!loading.value) {
//     page.value++
//   }
// }
const changeSelect = (event: any) => {
    console.log(event)
    tableData.value = []
    page.value = 0
    getDataList()
}
const onSearchFun = () => {
    tableData.value = []
    page.value = 0
    getDataList()
}



// 删除
const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除该条数据吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        // 调用删除接口
        const res = await deleteArticle({ articleId: row.id })
        if (res.data.code === 0) {
            ElMessage.success('删除成功')
            // 刷新列表
            tableData.value = []
            page.value = 0
            getDataList()
        } else {
            ElMessage.error(res.data.msg || '删除失败')
        }
    } catch {
        // 用户取消删除
    }
}

const handleFirstChangeType = async (row: any) => {
    if(userInfo.value.type != 1){
        return
    }
    console.log(row)
    await feedback.confirm('确定要更改状态为已达标待审核么')
    console.log('点击了确定')
    const res = await editFirstDeployTraffic({articleId: row.id})
    if (res.data.code == 0) {
        feedback.msgSuccess('修改成功')
        tableData.value = []
        page.value = 0
        getDataList()
    }else {
        feedback.msgError(res.data.msg || '修改失败')
    }
}
const handleSecondChangeType = async (row: any) => {
    if(userInfo.value.type != 1){
        return
    }
    if(row.isFirstDeployTraffic != 30){
        feedback.msgError('第一次投流还未成功投流')
        return
    }
    console.log(row)
    await feedback.confirm('确定要更改状态为已达标待审核么')
    console.log('点击了确定')
    const res = await editSecondDeployTraffic({articleId: row.id})
    if (res.data.code == 0) {
        feedback.msgSuccess('修改成功')
        tableData.value = []
        page.value = 0
        getDataList()
    }else {
        feedback.msgError(res.data.msg || '修改失败')
    }
}
const handleThreeChangeType = async (row: any) => {
    if(userInfo.value.type != 1){
        return
    }
    if(row.isSecondDeployTraffic != 30){
        feedback.msgError('第二次投流还未成功投流')
        return
    }
    console.log(row)
    await feedback.confirm('确定要更改状态为已达标待审核么')
    console.log('点击了确定')
    const res = await editThreeDeployTraffic({articleId: row.id})
    if (res.data.code == 0) {
        feedback.msgSuccess('修改成功')
        tableData.value = []
        page.value = 0
        getDataList()
    }else {
        feedback.msgError(res.data.msg || '修改失败')
    }
}

const getList = () => {
    tableData.value = []
    page.value = 0
    getDataList()
}

onMounted(() => {
    getDataList()
})
</script>

<style lang="less" scoped>
.gross-profit-calculator {
    /* padding: 20px; */
    background-color: #FAF8F8;
    height: 100vh;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 0;
    /* Override default el-header padding */
    height: auto;
    /* Adjust height */
    background-color: #fff;
    /* Header background for contrast if needed */
    padding: 15px 20px;
    border-radius: 4px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
}

.title-area {
    display: flex;
    align-items: center;
}

.page-title {
    font-size: 20px;
    /* font-weight: 600; */
    color: #3098F7;
    margin: 0;
}

.version-info,
.upgrade-info {
    font-size: 12px;
    color: #909399;
    margin-left: 15px;
}

.actions-area .el-button {
    margin-left: 10px;
}


.user-info {
    display: flex;
    align-items: center;
    gap: 15px;

    span {
        font-size: 14px;
        opacity: 0.9;
    }
}

// }

.table-container {
    padding: 20px 30px;
    overflow-x: auto;

    .opening-amount-container {
        display: flex;
        align-items: center;
    }

    .el-table {
        .el-tag {
            font-weight: 500;
        }

        .el-table__cell {
            padding: 8px 0;
            font-size: 12px;
        }

        :deep(.el-table__header-wrapper) {
            .el-table__header {
                th {
                    background-color: #909399 !important;
                    color: white !important;
                    font-weight: 600;
                }
            }
        }

        :deep(.el-table th.el-table__cell) {
            background-color: #909399 !important;
            color: white !important;
        }

        // 待处理状态行样式（青绿色）
        :deep(.status-pending) {
            background-color: #e0f2f1;
        }

    }
}

// 待处理状态行样式（青绿色）
:deep(.status-pending) {
    background-color: #e0f2f1;
}

// 已处理状态行样式（浅蓝色）
:deep(.status-processed) {
    background-color: #e3f2fd !important;
}

.excel-upload-container {
    max-width: 600px;
    margin: 30px auto;
}

.upload-progress {
    margin: 15px 0;
}

.upload-btn {
    margin-top: 10px;
}

.el-input__wrapper {
    border: none;
}

:deep(.headerClass) {
    background-color: #909399 !important;
    color: #333;
    .cell{
        padding-left: 5px !important;
        padding-right: 5px !important;
    }
}
:deep(.cellClass) {
    .cell{
        padding: 0 5px !important;
    }
}
:deep(.el-table){
    --el-border-color-lighter: #DCDCDC; /* 自定义颜色值 */
}
// 弹窗样式
.dialog-content {
    padding: 20px 0;
}

.dialog-footer {
    text-align: right;
}

.dialog-footer .el-button {
    margin-left: 10px;
}

.main-content{
    padding: 10px !important;
}
:deep(.el-input__prefix){
    width: 0 !important;
}


:deep(.el-scrollbar__bar.is-vertical){
    display: block !important;
    width: 15px !important;
    .el-scrollbar__thumb{
        opacity: 1 !important;
    }
}
:deep(.el-scrollbar__bar.is-horizontal){
    display: block !important;
    height: 15px !important;
    .el-scrollbar__thumb{
        opacity: 1 !important;
    }
}
</style>